package com.graduationproject.examonline.utils;

import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("api/token")
public class TokenController {

    @PostMapping("/verifyToken")
    public Result verifyToken(@RequestBody() Map<String, Object> params) {
        try {
            Map<String, Object> userInfo = (Map<String, Object>) params.get("userInfo");
            Claims body = Token.parseToken((String) params.get("token"), SingelKey.getInstance().getKey());
            Map<String, String> data = new HashMap<String, String>();
            data.put("userId", (String) body.get("userId"));
            data.put("userName", (String) body.get("userName"));
            data.put("identity", (String) body.get("identity"));
            if (body != null) {
                boolean flag = true;
                if (userInfo != null && body != null) {
                    String userId1 = (String) userInfo.get("userId");
                    String userName1 = (String) userInfo.get("userName");
                    String identity1 = (String) userInfo.get("identity");

                    String userId2 = (String) body.get("userId");
                    String userName2 = (String) body.get("userName");
                    String identity2 = (String) body.get("identity");

                    if (!userId1.equals(userId2)) {
                        flag = false;
                    }
                    if (!userName1.equals(userName2)) {
                        flag = false;
                    }
                    if (!identity1.equals(identity2)) {
                        flag = false;
                    }
                }
                if (flag) {
                    return new Result(0, 200, "验证成功", data);
                }
                return new Result(1, 200, "验证用户信息失败");
            }
            System.out.println("(" + new Date().toString() + ")验证token失败：" + params.get("token"));
            return new Result(1, 200, "验证失败");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("(" + new Date().toString() + ")验证token失败：" + params.get("token"));
            return new Result(1, 500, "验证失败");
        }
    }
}
